<template>
	<view class="content">
		<label class="line" v-show="stateType != 1 || (stateType == 1 && article_label_type == 0)">
			<input disabled="false" :value="sortList[sortIndex]" class="input" placeholder="请选择分类" placeholder-class="inputActive" />
			<picker @change="bindPickerChangeText" :value="sortIndex" :range="sortList"><i class="iconfont iconjiantou"></i></picker>
		</label>
		<textarea class="cont" v-model="title" placeholder="请输入标题（5~30个字）" maxlength="30" placeholder-style="color: #999999;font-size: 38upx;" @input="changeInput" />
		<view class="container">
			<view class='wrapper'>
				<view class='toolbar' @tap="format">
					<view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold"></view>
					<view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti" data-name="italic"></view>
					<view :class="formats.underline ? 'ql-active' : ''" class="iconfont icon-zitixiahuaxian" data-name="underline"></view>
					<view :class="formats.strike ? 'ql-active' : ''" class="iconfont icon-zitishanchuxian" data-name="strike"></view>
					<view :class="formats.align === 'left' ? 'ql-active' : ''" class="iconfont icon-zuoduiqi" data-name="align" data-value="left"></view>
					<view :class="formats.align === 'center' ? 'ql-active' : ''" class="iconfont icon-juzhongduiqi" data-name="align" data-value="center"></view>
					<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi" data-name="align" data-value="right"></view>
					<view :class="formats.align === 'justify' ? 'ql-active' : ''" class="iconfont icon-zuoyouduiqi" data-name="align" data-value="justify"></view>
					<view :class="formats.lineHeight ? 'ql-active' : ''" class="iconfont icon-line-height" data-name="lineHeight" data-value="2"></view>
					<view :class="formats.letterSpacing ? 'ql-active' : ''" class="iconfont icon-Character-Spacing" data-name="letterSpacing" data-value="2em"></view>
					<view :class="formats.marginTop ? 'ql-active' : ''" class="iconfont icon-722bianjiqi_duanqianju" data-name="marginTop" data-value="40upx"></view>
					<view :class="formats.micon-previewarginBottom ? 'ql-active' : ''" class="iconfont icon-723bianjiqi_duanhouju" data-name="marginBottom" data-value="40upx"></view>
					<view class="iconfont icon-clearedformat" @tap="removeFormat"></view>
					<view :class="formats.fontFamily ? 'ql-active' : ''" class="iconfont icon-font" data-name="fontFamily" data-value="Pacifico"></view>
					<view :class="formats.fontSize === '48upx' ? 'ql-active' : ''" class="iconfont icon-fontsize" data-name="fontSize" data-value="48upx"></view>
			
					<view :class="formats.color === '#0000ff' ? 'ql-active' : ''" class="iconfont icon-text_color" data-name="color" data-value="#0000ff"></view>
					<view :class="formats.backgroundColor === '#00ff00' ? 'ql-active' : ''" class="iconfont icon-fontbgcolor" data-name="backgroundColor" data-value="#00ff00"></view>
			
					<view class="iconfont icon-date" @tap="insertDate"></view>
					<view class="iconfont icon--checklist" data-name="list" data-value="check"></view>
					<view :class="formats.list === 'ordered' ? 'ql-active' : ''" class="iconfont icon-youxupailie" data-name="list" data-value="ordered"></view>
					<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie" data-name="list" data-value="bullet"></view>
					<view class="iconfont icon-undo" @tap="undo"></view>
					<view class="iconfont icon-redo" @tap="redo"></view>
			
					<view class="iconfont icon-outdent" data-name="indent" data-value="-1"></view>
					<view class="iconfont icon-indent" data-name="indent" data-value="+1"></view>
					<view class="iconfont icon-fengexian" @tap="insertDivider"></view>
					<view class="iconfont icon-charutupian" @tap="insertImage" v-show="addType != 2"></view>
					<view :class="formats.header === 1 ? 'ql-active' : ''" class="iconfont icon-format-header-1" data-name="header" :data-value="1"></view>
					<view :class="formats.script === 'sub' ? 'ql-active' : ''" class="iconfont icon-zitixiabiao" data-name="script" data-value="sub"></view>
					<view :class="formats.script === 'super' ? 'ql-active' : ''" class="iconfont icon-zitishangbiao" data-name="script" data-value="super"></view>
					<view class="iconfont icon-shanchu" @tap="clear"></view>
					<view :class="formats.direction === 'rtl' ? 'ql-active' : ''" class="iconfont icon-direction-rtl" data-name="direction" data-value="rtl"></view>
					<view class="iconfont iconshipin1" @tap="insertVideo" v-show="addType != 2"></view>
				</view>
				<editor id="editor" class="ql-container" placeholder="开始输入..." placeholder-class="editorActive" showImgSize showImgToolbar showImgResize @statuschange="onStatusChange"></editor>
			</view>
		</view>
	</view>
</template>

<script>
	import mpvuePicker from '@/components/mpvue-picker/mpvuePicker.vue';
	export default{
		components: {
			mpvuePicker
		},
		data() {
			return {
				tips: [
					[{ name: '理想', tipstype: 1 }, { name: '学业规划', tipstype: 2 }, { name: '职业规划', tipstype: 3 }],
					[{ name: '成绩', tipstype: 4 }, { name: '评语', tipstype: 5 }, { name: '获奖', tipstype: 6 }],
					[{ name: '兴趣', tipstype: 7 }, { name: '特长', tipstype: 8 }],
					[{ name: '家规', tipstype: 9 }, { name: '祖训', tipstype: 10 }, { name: '祖传', tipstype: 13 }, { name: '家务', tipstype: 11 }, { name: '兴家', tipstype: 12 }]
				],
				sortList: [], //类型名称列表
				sortValue: [], //类型值列表
				sortIndex: 0, //类型索引值
				sign:'',
				title: '',
				content: '',
				formats: {},
				remnant: 0, //文本域内容的长度
				stateType: '', // 0为默认抖教文章
				addType: '', //附加条件: 0+0为首页抖教推荐  0+1为智囊团  1+3为家文化&孩子-目标、成长、才艺  2+2为育儿经&育儿经-我的  3+4为我的智囊团
				article_id: '', //文章ID
				article_type: 1, //1目标，2成长，3才艺, 4家文化
				article_label_type: 1 ,//0全部 1理想，2学习规划，3职业规划，4成绩，5评语，6奖状，7兴趣，8特长 9家规 10祖训 11家务 12兴家 13祖传
				releaseType: 1
			}
		},
		onNavigationBarButtonTap() {
			this.getContents();
		},
		onLoad(e) {
			this.stateType = e.stateType;
			this.addType = e.addType;
			this.article_id = e.article_id;
			if (this.stateType == 0 || this.stateType == 2 || this.stateType == 3) {
				if(e.releaseType) {
					this.releaseType = e.releaseType;
				}
				this.getTypes();
			} else if(this.stateType == 1) {
				this.article_type = e.article_type;
				this.article_label_type = 0;
				var arr1 = []; //保存类型名称
				var arr2 = []; //保存类型值
				for (let i = 0; i < this.tips[this.article_type - 1].length; i++) {
					arr1[i] = this.tips[this.article_type - 1][i].name;
					arr2[i] = this.tips[this.article_type - 1][i].tipstype;
				}
				this.sortList = arr1;
				this.sortValue = arr2;
			}
			uni.loadFontFace({
				family: 'Pacifico',
				source: 'url("https://sungd.github.io/Pacifico.ttf")'
			})
			this.$zapi.apiPost('user/App/getsign').then(res=>{
				if(res.data.code==200){
					this.sign = res.data.data.sign;
				}
			});
			this.getDetail();
		},
		methods:{
			// 获取类型列表
			getTypes() {
				var url = '';
				if(this.stateType == 0 && this.addType != 1) {
					url = 'user/article.Lists/listType'
				} else if(this.stateType == 2) {
					url = 'user/information.Lists/listType'
				} else if (this.stateType == 3) {
					url = 'user/wisdom.Lists/listType'
				}
				this.$zapi.apiPost(url).then(res=> {
					if (res.data.code == 200) {
						var arr = res.data.data
						var arr1 = []; //保存类型名称
						var arr2 = []; //保存类型值
						if(this.stateType == 0 || this.stateType == 3) {
							arr.forEach(item => {
								arr1.push(item.article_name)
								arr2.push(item.article_type_id)
							})
						} else if(this.stateType == 2) {
							arr.forEach(item => {
								arr1.push(item.im_type_name)
								arr2.push(item.im_type_id)
							})
						}
						this.sortList = arr1
						this.sortValue = arr2
					}
				})
			},
			/* 修改文章 */
			finish(){
				var url = '';
				this.content = this.content.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
				var data = {
					title: this.title,
					content: this.content,
					sign: this.sign
				};
				if(this.stateType == 0 && this.addType != 1) {
					url = 'user/article.Lists/eidtArticle'
					data.article_type_id = this.sortValue[this.sortIndex]
					data.article_id = this.article_id
				} else if (this.stateType == 1) {
					url = 'user/newarticle.Lists/eidtArticle'
					data.article_type = this.article_type
					data.patriarch_article_id = this.article_id
					if (this.article_label_type == 0) {
						data.article_label_type = this.sortValue[this.sortIndex]
					} else {
						data.article_label_type = this.article_label_type;
					}
					if (this.article_type != 4) {
						data.child_user_id = uni.getStorageSync('currentChild').student_id;
					}
				} else if (this.stateType == 2) {
					url = 'user/information.Lists/addInformation'
					data.im_title = this.title
					data.im_content = this.content
					data.im_type_id = this.sortValue[this.sortIndex]
					data.im_id = this.article_id
				} else if (this.stateType == 3) {
					url = 'user/wisdom.Lists/eidtArticle'
					data.article_type_id = this.sortValue[this.sortIndex]
					data.article_id = this.article_id
				}
				
				if (!data.content) {
					uni.showToast({
						title: '请填写文章内容',
						icon: 'none'
					});
				} else if (!data.title) {
					uni.showToast({
						title: '请填写文章标题',
						icon: 'none'
					});
				} else {
					this.$zapi.apiPost(url, data).then(res => {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						});
						var article_id = '';
						if(this.stateType == 0 || this.stateType == 3) {
							article_id = res.data.data.article_id;
						}
						if(res.data.code == 200){
							setTimeout(function(){
								uni.navigateBack({
									delta: 1
								})
							},1000)
						}
					});
				}
			},
			/* 获取文章详情 */
			getDetail() {
				var url = '';
				var data = {}
				if(this.stateType == 0 && this.addType != 1) {
					url = 'user/article.Lists/articleList'
					data.article_id = this.article_id
				} else if(this.stateType == 1) {
					url = 'user/newarticle.Lists/articleList';
					data.patriarch_article_id = this.article_id
				} else if (this.stateType == 2) {
					url = 'user/information.Lists/InformationList';
					data.im_id = this.article_id
					if(this.releaseType != 1) {
						data.is_show = this.releaseType
					}
				} else if (this.stateType == 3) {
					url = 'user/wisdom.Lists/articleList'
					data.article_id = this.article_id
				}
				this.$zapi.apiPost(url,data).then(res=>{
					if(res.data.code == 200) {
						var result = res.data.data.data[0];
						if(this.stateType == 2) {
							result['title'] = result.im_title
							result['content'] = result.im_content
							result['article_label_type'] = result.im_type_id
						}
						result.content = result.content.replace(/&lt;videoSrc=/g, '<video src="');
						result.content = result.content.replace(/video&gt;/g,
							'"autoplay="true" loop="true" show-center-play-btn="true" show-play-btn="false"></video>');
						result.content = result.content.replace(/src=/g, 'style="max-width:100%;" src=');
						this.title = result.title;
						this.content = result.content;
						for(var i = 0; i < this.sortValue.length; i++) {
							if(result.article_label_type == this.sortValue[i]) {
								this.sortIndex = i;
							}
						}
						this.onEditorReady();
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
					}
				})
			},
			/* 改变标题内容 */
			changeInput(e){
				this.title = e.target.value;
				this.remnant = e.detail.cursor;
				if(this.remnant >= 30) {
					uni.showToast({
						title: '最多只能输入30个字',
						icon: 'none'
					})
				}
			},
			/* 选择分类 */
			bindPickerChangeText: function(e) {
				this.sortIndex = e.target.value;
			},
			/* 编辑器初始化 */
			onEditorReady() {
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context;
					this.setContents();
				}).exec()
			},
			/* 撤销至上一步 */
			undo() {
				this.editorCtx.undo()
			},
			/* 恢复至下一步 */
			redo() {
				this.editorCtx.redo()
			},
			/* 获取富文本支持设置的样式 */
			format(e) {
				let {
					name,
					value
				} = e.target.dataset
				if (!name) return
				this.editorCtx.format(name, value)
			},
			/* 通过 Context 方法改变编辑器内样式时触发，返回选区已设置的样式 */
			onStatusChange(e) {
				const formats = e.detail
				this.formats = formats
			},
			/* 插入分割线 */
			insertDivider() {
				this.editorCtx.insertDivider({
					success: function() {
						// console.log('insert divider success')
					}
				})
			},
			/* 清空编辑器内容 */
			clear() {
				this.editorCtx.clear({
					success: function(res) {
						// console.log("clear success")
					}
				})
			},
			/* 清除当前选区的样式 */
			removeFormat() {
				this.editorCtx.removeFormat()
			},
			/* 覆盖当前选区,插入当前日期 */
			insertDate() {
				const date = new Date()
				const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
				this.editorCtx.insertText({
					text: formatDate
				})
			},
			/* 插入图片 */
			insertImage() {
				var _this = this;
				uni.chooseImage({
					count: 1,
					success: (res) => {
						_this.$zapi.apifile('user/currency.basic/UploadUserImg',{file:res.tempFilePaths[0]}).then(res=>{
							var result = JSON.parse(res.data);
							if(result.code == 200) {
								var url = result.data.visit_path;
								_this.editorCtx.insertImage({
									src: url,
									alt: '图像',
									success: function() {
										// console.log('insert image success')
									}
								});
							} else {
								uni.showToast({
									title: '上传失败',
									icon: 'none'
								})
							}
						})
					}
				})
			},
			/* 插入视频 */
			insertVideo() {
				var _this = this;
				uni.chooseVideo({
					count: 1,
					success: res => {
						uni.showLoading({
							title: '上传中'
						});
						_this.$zapi.apifile('user/currency.basic/UploadVideo',{file:res.tempFilePath}).then(res=>{
							var result = JSON.parse(res.data);
							if(result.code == 200) {
								var url = result.data.visit_path;
								var cont = '<video src="'+url+'"><video>';
								_this.editorCtx.insertText({
									text: cont,
									success: function(res) {
										// console.log(res);
									}
								});
							} else {
								uni.showToast({
									title: '上传失败',
									icon: 'none'
								})
							}
							uni.hideLoading();
						})
					}
				});
			},
			/* 获取编辑器内容 */
			getContents(){
				var _this = this;
				_this.editorCtx.getContents({
					success: function(res) {
						_this.content = res.html;
						_this.finish();
					}
				})
			},
			/* 设置富文本框初始值 */
			setContents(){
				var _this = this;
				_this.editorCtx.setContents({
					html: _this.content,
					success: function(res) {
						// console.log(res);
					}
				})
			}
		},
		mounted() {
			
		}
	}
</script>

<style>
	@import "../../common/editor-icon.css";
	page{
		background: #FAFAFA;
	}
	.line{
		width: 690upx;
		padding: 0 30upx;
		height: 90upx;
		display: flex;
		flex-direction: row;
		align-items: center;
		background: #ffffff;
		justify-content: space-between;
		margin-bottom: 16upx;
	}
	.inputActive{
		font-size: 32upx;
		color: #999999;
	}
	.iconjiantou{
		color: #999999;
	}
	.cont{
		width: 690upx;
		padding: 30upx;
		background: #FFFFFF;
		margin-bottom: 16upx;
		font-size: 38upx;
		height: 150upx;
	}
	.container {
		padding: 30upx;
		background-color: #FFFFFF;
	}

	.editorActive{
		color: #999999;
		font-size: 32upx;
		font-family: Source Han Sans CN;
		font-weight:400;
	}
	
	.container .iconfont{
		display: inline-block;
		padding: 16upx 16upx;
		width: 48upx;
		height: 48upx;
		cursor: pointer;
		font-size: 40upx;
		line-height: 1;
	}
	.container .iconshipin1{
		display: inline-block;
		padding: 16upx 10upx;
		width: 60upx;
		height: 48upx;
		cursor: pointer;
		font-size: 50upx;
		line-height: 1;
	}
	
	.toolbar {
		box-sizing: border-box;
		border-bottom: 0;
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
	}
	
	
	.ql-container {
		box-sizing: border-box;
		width: 100%;
		min-height: 50vh;
		height: auto;
		background: #fff;
		margin-top: 40upx;
		font-size: 32upx;
		line-height: 1.5;
	}
	
	.ql-active {
		color: #06c;
	}
</style>
